package com.sdx.console.chart.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.console.common.entity.BaseProvince;
import com.sdx.console.saas.entity.SaasTenant;
import com.sdx.console.utils.BigDecimalUntil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.ext.fn.StringUtil;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CustomerChartController
 * @Description
 * @Author kangbin
 * @Date 2019/12/4 14:57
 */
@Controller
@RequestMapping("/chart/customer")
public class CustomerChartController extends AuthorizedBaesController {

    private static final Logger log = LoggerFactory.getLogger(CustomerChartController.class);
    private static final String MODEL = "/chart/customer";
    private static final String SQL = "chart.customer";

    @Resource
    private SQLManager sqlManager;

    @Autowired
    private CorePlatformService platformService;

    private void setPageParam(ModelAndView view, HttpServletRequest request) {
        Integer accessType = platformService.getAccessType(request);
        view.addObject("accessType",accessType);
        if (accessType==6) {
            SaasTenant param = new SaasTenant();
            param.setTenantStatus(1);
            List<SaasTenant> tenantList = sqlManager.template(param);
            view.addObject("tenantList", tenantList);
        }
    }

    @GetMapping("/index.do")
    @Function("chart.customer.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }


    @PostMapping("/histogram.json")
    @Function("chart.customer.query")
    @ResponseBody
    public JsonResult histogram(String provIds,String type,Integer year,HttpServletRequest request,Integer tenantId) {
        CoreUser user = getLoginUser(request);
        Integer accessType = platformService.getAccessType(request);
        Map<String,Object> param = new HashMap<>();
        param.put("provIds",provIds);
        param.put("year",year);
        param.put("tenantId",user.getTenantId());
        if(accessType==6&&tenantId!=null){
            param.put("tenantId",tenantId);
        }
        param = init(type, param);
        List<BaseEntity> lists = sqlManager.select(SQL + ".selectCountProvDrilldown", BaseEntity.class,param);
        String name = "";
        JSONArray array =  new JSONArray();
        List<JSONObject> jsonList = new ArrayList<>();
        JSONObject json = new JSONObject();
        for (BaseEntity entity : lists) {
            String id = entity.get("id").toString();
            if(!name.equals(id)){
                array = new JSONArray();
                json = new JSONObject();
                json.put("name",id+"月");
                json.put("id",id+"月");
                jsonList.add(json);
                json.put("data",array);
                name = id;
            }
            Object[] obj = new Object[2];
            obj[0]=entity.get("provName");
            obj[1]=entity.get("total");
            array.add(obj);
        }
        List<BaseEntity> list = sqlManager.select(SQL + ".selectCountProv", BaseEntity.class,param);
        List<JSONObject> objects = new ArrayList<>();
        for (BaseEntity baseEntity : list) {
            JSONObject object = new JSONObject();
            object.put("name",baseEntity.get("id").toString()+"月");
            object.put("y",baseEntity.get("total"));
            object.put("drilldown",baseEntity.get("id").toString()+"月");
            objects.add(object);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",objects);
        jsonObject.put("series",jsonList);
        return JsonResult.success(jsonObject);
    }


    @PostMapping("/piechart.json")
    @Function("chart.customer.query")
    @ResponseBody
    public JsonResult piechart(String provIds,String type,Integer year,HttpServletRequest request,Integer tenantId) {
        CoreUser user = getLoginUser(request);
        Integer accessType = platformService.getAccessType(request);
        Map<String,Object> param = new HashMap<>();
        param.put("provIds",provIds);
        param.put("year",year);
        param.put("tenantId",user.getTenantId());
        if(accessType==6&&tenantId!=null){
            param.put("tenantId",tenantId);
        }
        param = init(type, param);
        List<BaseEntity> lists = sqlManager.select(SQL + ".selectPieChart", BaseEntity.class,param);
        Integer count = sqlManager.intValue(SQL + ".selectPieChartCount", param);
        List<JSONObject> list = new ArrayList<>();
        for (BaseEntity baseEntity : lists) {
            JSONObject json = new JSONObject();
            json.put("count",baseEntity.get("total"));
            json.put("name",baseEntity.get("provName"));
            Double rate = 0d;
            if(count>0){
               rate =  BigDecimalUntil.rate(Integer.parseInt(baseEntity.get("total").toString()),count,2);
            }
            json.put("y", rate);
            list.add(json);
        }
        return JsonResult.success(list);
    }


    @PostMapping("/curve.json")
    @Function("chart.customer.query")
    @ResponseBody
    public JsonResult curve(String provIds,String type,Integer year,HttpServletRequest request,Integer tenantId) {
        CoreUser user = getLoginUser(request);
        Integer accessType = platformService.getAccessType(request);
        Map<String,Object> param = new HashMap<>();
        param.put("provIds",provIds);
        param.put("year",year);
        param.put("tenantId",user.getTenantId());
        if(accessType==6&&tenantId!=null){
            param.put("tenantId",tenantId);
        }
        param = init(type, param);
        List<BaseEntity> lists = sqlManager.select(SQL + ".selectCurve", BaseEntity.class,param);
        String name = "";
        List<JSONObject> jsonList = new ArrayList<>();
        JSONObject json = new JSONObject();
        int[] ints = new int[12];
        for (int i = 0; i < lists.size(); i++) {
            BaseEntity entity = lists.get(i);
            String provName = entity.get("provName").toString();
            if(!name.equals(provName)){
                ints = new int[12];
                json = new JSONObject();
                json.put("name",provName);
                jsonList.add(json);
                json.put("data",ints);
                name = provName;
            }
            ints[i%12] = Integer.parseInt(entity.get("total").toString());
        }
        return JsonResult.success(jsonList);
    }

    @PostMapping("/getProv.json")
    @ResponseBody
    public List<BaseProvince> getProv(HttpServletRequest request) {
        return sqlManager.select(SQL+".getProv",BaseProvince.class);
    }

    public Map<String,Object> init(String type,Map<String,Object> param){
        if(StringUtils.isNotEmpty(type)){
            String[] str = type.split(",");
            StringBuffer finSQL = new StringBuffer() ;
            StringBuffer roleSQL = new StringBuffer() ;
            roleSQL.append("( ");
            for (String s : str) {
                if("1".equals(s)){
                    finSQL.append("##");
                }else if("2".equals(s)){
                    roleSQL.append(" role.right_source = 2 or");
                }else if("3".equals(s)){
                    roleSQL.append(" role.role_id = 1 or");
                }else if("4".equals(s)){
                    roleSQL.append(" role.role_id = 3 or");
                }else if("5".equals(s)){
                    roleSQL.append(" role.right_source = 3 or");
                }else if("6".equals(s)){
                    roleSQL.append(" role.right_source = 5 or");
                }else if("7".equals(s)){
                    roleSQL.append(" role.role_id = 2 or");
                }
            }
            roleSQL.deleteCharAt(roleSQL.length()-1);
            roleSQL.deleteCharAt(roleSQL.length()-1);
            roleSQL.append(")");
            param.put("finSQL",finSQL.toString());
            param.put("roleSQL",roleSQL.toString());
        }
        return param;
    }
}
